package com.junxonline.instant.api.handler;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.log4j.Log4j2;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * Mybatis Plus自动填充
 *
 * @author JunX
 * @date 2021-06-25
 */
@Log4j2
@Component
public class MybatisPlusMetaHandler implements MetaObjectHandler {

    /**
     * 插入时自动填充
     *
     * @param metaObject metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        final Date currentTime = DateUtil.date();
        this.strictInsertFill(metaObject, "createTime", () -> currentTime, Date.class);
        this.strictInsertFill(metaObject, "updateTime", () -> currentTime, Date.class);
    }

    /**
     * 更新时自动填充
     *
     * @param metaObject metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        final Date currentTime = DateUtil.date();
        this.strictUpdateFill(metaObject, "updateTime", () -> currentTime, Date.class);
    }

    /**
     * 修改 Mybatis Plus 自动填充策略
     * @param metaObject metaObject
     * @param fieldName fieldName
     * @param fieldVal fieldVal
     * @return MetaObjectHandler
     */
    @Override
    public MetaObjectHandler strictFillStrategy(MetaObject metaObject, String fieldName, Supplier<?> fieldVal) {
            // 修改策略 => 不管值是不是Null都执行自动填充
            Object obj = fieldVal.get();
            if (Objects.nonNull(obj)) {
                metaObject.setValue(fieldName, obj);
            }
        return this;
    }

}
